'''
模拟相机
'''
import glob
import threading
import time

import cv2

# try:
#     from global_vars import program_config_dict
# except:
#     program_config_dict = {
#         'sim_camera':{
#             'ip_img_dict': {
#                 '192.168.0.10': r'D:\data\240507fubatianxian\other\*.jpg',
#             }
#         }
#     }
class SimCamera:

    def __init__(self, ip_str, triggermode='off', frame_callback=None): # img_dir
        pass
        # self.img_glob = ip_str
        self.ls = glob.glob(ip_str)
        # self.ls = glob.glob(program_config_dict['sim_camera']['ip_img_dict'][ip_str])
        self.ind = -1
        print(f'已打开模拟相机 {ip_str}')

        if triggermode == 'hard':
            if frame_callback is None:
                raise Exception('')
            self.frame_callback = frame_callback
            self.h_thread_handle = threading.Thread(
                target=self.Work_thread, daemon=True)
            self.h_thread_handle.start()

    def Work_thread(self):
        time.sleep(5)
        while True:
            # time.sleep(3)
            if len(self.ls)==15*7:
                tt = 15
            else:
                tt = 9
            if (self.ind+1)%tt==0 and self.ind>1:
                delay = 10 if tt==15 else 15*1.5+10-9*1.5
                time.sleep(delay)
                # import msvcrt
                # print("按下任意键继续...")
                # msvcrt.getch()
                # print("检测到按键！程序继续运行...")
            else:
                time.sleep(1.5)


            self.frame_callback(self.getFrame())


    def getFrame(self, ExposureTime=0):
        if len(self.ls) == 0:
            return None
        self.ind = (self.ind+1)%len(self.ls)
        img = cv2.imread(self.ls[self.ind])
        return img

    def close(self):
        pass

    def setExposureTime(self,et=0):
        pass

if __name__ == '__main__':
    cam = SimCamera('192.168.0.10')
    while 1:
        img = cam.getFrame()
        img = cv2.resize(img,(640,640))
        cv2.imshow('xx',img)
        cv2.waitKey(0)